<script setup lang="tsx">
// import dayjs from 'dayjs';
import { AddIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { inject, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRoute } from 'vue-router';

import { add, Delete, edit, getInfo, getList } from '@/api/system/dict/data';
import { getList as getDictTypeList } from '@/api/system/dict/type';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';

const { t } = useI18n();
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const columns = [
  {
    title: '字典编码',
    colKey: 'dictCode',
  },
  {
    title: '字典标签',
    colKey: 'dictLabel',
  },
  {
    title: '字典健值',
    colKey: 'dictValue',
  },
  {
    title: '字典排序',
    colKey: 'dictSort',
  },
  {
    title: '状态',
    colKey: 'status',
  },
  {
    title: '备注',
    colKey: 'remark',
  },
  {
    title: '创建时间',
    colKey: 'createTime',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface QueryFormType {
  dictCode: string | null;
  dictLabel: string | null;
  status: string | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
  dictName: string | null;
}
const INITIAL_QUERYFORM: QueryFormType = {
  dictCode: null,
  dictLabel: null,
  status: null,
  pageNum: null,
  pageSize: null,
  dictName: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
// const balanceRange = ref<[number | null, number | null]>([null, null]);
const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.dictLabel} placeholder="字典标签" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>

      <t-select v-model={queryForm.value.status} placeholder="状态" style="width: 240px;">
        <t-option value="" label="全部" />
        <t-option value="0" label="正常" />
        <t-option value="1" label="停用" />
      </t-select>

      <t-select
        v-model={queryForm.value.dictName}
        placeholder="请选择字典类型"
        style="width: 240px;"
        clearable
        options={dictTypeOptions.value.map((item) => ({
          label: item.dictName,
          value: item.dictName,
        }))}
        onChange={onDictTypeChange}
      />
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="dictCode"
      onUnGetList={unGetList}
    >
      {{
        status: (slotProps: any) => (
          <t-tag theme={slotProps.row.status == 0 ? 'primary' : 'danger'} variant="light">
            {slotProps.row.status == 0 ? '正常' : '停用'}
          </t-tag>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const route = useRoute();
// const router = useRouter();
const dictTypeParam = ref(route.query.dictType || '');
const dictTypeOptions = ref<{ dictId: string | number; dictName: string; dictType: string }[]>([]);

// 查询时只查当前字典类型
const unGetList = async () => {
  try {
    const params: any = {
      dictCode: queryForm.value.dictCode ? Number(queryForm.value.dictCode) : null,
      dictLabel: queryForm.value.dictLabel,
      dictType: dictTypeParam.value,
      status: queryForm.value.status,
      pageNum: pagination.value.defaultCurrent,
      pageSize: pagination.value.defaultPageSize,
    };
    if (dateRange.value && dateRange.value.length === 2 && dateRange.value[0] && dateRange.value[1]) {
      // params.beginTime =
      //   typeof dateRange.value[0] === 'string' ? dateRange.value[0] : dayjs(dateRange.value[0]).format('YYYY-MM-DD');
      // params.endTime =
      //   typeof dateRange.value[1] === 'string' ? dateRange.value[1] : dayjs(dateRange.value[1]).format('YYYY-MM-DD');
    }
    const res = await getList(params);
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
    console.log('dateRange.value', dateRange.value);
  }
};

// 页面加载时自动查询
onMounted(async () => {
  const res = await getDictTypeList({ pageNum: 1, pageSize: 1000 });
  dictTypeOptions.value = res.rows || [];
  unGetList();
});

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  dateRange.value = [];
  pagination.value.defaultCurrent = 1;
  unGetList();
};
/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加字典', { dictType: dictTypeParam.value }, '添加字典');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '添加字典',
  '添加字典',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {
    dictLabel: [{ required: true, message: '字典标签不能为空', trigger: 'blur' }],
    dictValue: [{ required: true, message: '字典键值不能为空', trigger: 'blur' }],
    dictSort: [{ required: true, message: '字典排序不能为空', trigger: 'blur' }],
    dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
  },
);

// 修改
const unEdit = async (slotProps: any) => {
  const id = slotProps.row.dictId ?? slotProps.row.dictCode;
  if (!id) {
    MessagePlugin.error('未获取到字典主键，无法编辑');
    return;
  }
  try {
    const res = await getInfo(id);
    formObj.show(
      '编辑字典类型',
      {
        ...res.data,
        dictType: res.data.dictType,
      },
      '编辑字典类型',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑字典类型',
  '编辑字典类型',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {
    dictLabel: [{ required: true, message: '字典标签不能为空', trigger: 'blur' }],
    dictValue: [{ required: true, message: '字典键值不能为空', trigger: 'blur' }],
    dictSort: [{ required: true, message: '字典排序不能为空', trigger: 'blur' }],
    dictType: [{ required: true, message: '字典类型不能为空', trigger: 'blur' }],
  },
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref<(string | number)[]>([]);

const onConfirmDelete = () => {
  const ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;

  deleteId.value = isSingle ? value.map((item: any) => item.dictCode) : [value.row.dictCode];
};

// 下拉选择
const onDictTypeChange = (dictName: string) => {
  const item = dictTypeOptions.value.find((i) => i.dictName === dictName);
  if (item) {
    dictTypeParam.value = item.dictType;
    unGetList();
  }
};
</script>

<template>
  <div>
    <render />
    <form-dialog-group :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 编辑字典类型弹窗 -->
        <template v-if="item === '编辑字典类型'">
          <t-form-item label="字典标签" name="dictLabel">
            <t-input v-model="formData.dictLabel" placeholder="请输入字典标签" />
          </t-form-item>
          <t-form-item label="字典键值" name="dictValue">
            <t-input v-model="formData.dictValue" placeholder="请输入字典键值" />
          </t-form-item>
          <t-form-item label="字典排序" name="dictSort">
            <t-input v-model="formData.dictSort" placeholder="请输入字典排序" />
          </t-form-item>
          <t-form-item label="字典类型" name="dictType">
            <t-input v-model="formData.dictType" disabled />
          </t-form-item>
          <t-form-item label="状态" name="status">
            <t-select v-model="formData.status" placeholder="请选择状态">
              <t-option value="0" label="正常" />
              <t-option value="1" label="停用" />
            </t-select>
          </t-form-item>
          <t-form-item label="备注" name="remark">
            <t-input v-model="formData.remark" placeholder="请输入备注" />
          </t-form-item>
          <t-form-item label="创建人" name="createBy">
            <t-input v-model="formData.createBy" disabled />
          </t-form-item>
          <t-form-item label="创建时间" name="createTime">
            <t-input v-model="formData.createTime" disabled />
          </t-form-item>
        </template>
        <!-- 添加弹窗（添加字典类型） -->
        <template v-else-if="item === '添加字典'">
          <t-form-item label="字典标签" name="dictLabel">
            <t-input v-model="formData.dictLabel" placeholder="请输入字典标签" />
          </t-form-item>
          <t-form-item label="字典键值" name="dictValue">
            <t-input v-model="formData.dictValue" placeholder="请输入字典键值" />
          </t-form-item>
          <t-form-item label="字典排序" name="dictSort">
            <t-input v-model="formData.dictSort" placeholder="请输入字典排序" />
          </t-form-item>
          <t-form-item label="字典类型" name="dictType">
            <t-input v-model="formData.dictType" disabled />
          </t-form-item>
          <t-form-item label="状态" name="status">
            <t-select v-model="formData.status" placeholder="请选择状态">
              <t-option value="0" label="正常" />
              <t-option value="1" label="停用" />
            </t-select>
          </t-form-item>
          <t-form-item label="备注" name="remark">
            <t-input v-model="formData.remark" placeholder="请输入备注" />
          </t-form-item>
        </template>
      </template>
    </form-dialog-group>
    <t-dialog v-model:visible="confirmVisible" header="确认删除当前所选项目？" body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete" />
  </div>
</template>
